package com.atguigu.springboot.controller;

import com.atguigu.springboot.exception.UserNotExistException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义异常处理器
 *
 * @author: ybl
 * @create: 2019-05-16 00:34
 **/
@ControllerAdvice  //异常处理器需要添加的注解,声明为spring的组件
public class MyExceptionHandler {

    //1.这种处理浏览器跟客户端都是返回json数据,无法自适应
    //自定义指定异常时处理
//    @ExceptionHandler(UserNotExistException.class)
//    @ResponseBody
//    public Map<String, Object> hanblerException(Exception e) {
//        Map<String, Object> map = new HashMap<>();
//        map.put("code", "user.notExist");
//        map.put("message", e.getMessage());
//
//        return map;
//    }

    /*
    Integer statusCode = (Integer) request
         .getAttribute("javax.servlet.error.status_code");
     */
    @ExceptionHandler(UserNotExistException.class)
    public String hanblerException(Exception e, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", "user.notExist");
        map.put("message", "你找不到这个用户的");

        //将自定义的参数添加到request域
        request.setAttribute("ext", map);

        //自定义异常信息时,一定要配置springBoot自动配置的状态码
        request.setAttribute("javax.servlet.error.status_code", 500);
        //转发到/error,
        return "forward:/error";
    }

}
